<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 深拷贝:拷贝出来的目标对象的和原目标对象,相互之间互不影响.修改其中一个对象,两外一个对象不会进行影响
        var obj = {
            name: '张美丽',
            age: 20,
            hobby: ['运动', '敲代码', '谈恋爱'],
            school: {
                id: 'y001',
                sname: '姚班'
            }
        };
        var copyObj = {};
        // 1.for..in进行深拷贝
        function deepCopy(newObj, oldObj) {
            for (var key in oldObj) {
                // 1.获取对象的每项属性或方法的值
                var item = oldObj[key];
                if (item instanceof Array) {
                    // 2.如果是复杂数据类型,就遍历进行一个个赋值
                    newObj[key] = [];
                    deepCopy(newObj[key], item);
                } else if (item instanceof Object) {
                    newObj[key] = {};
                    console.log(item);
                    deepCopy(newObj[key], item);
                } else {
                    newObj[key] = item;
                }
            }
        };
        deepCopy(copyObj, obj);
        // 修改拷贝后的对象
        copyObj.hobby[0] = '读书';
        copyObj.school.id = 'y002';
        console.log(copyObj);
        console.log(obj);
    </script>
</body>

</html>